<template>
  <div class="container">
    <van-loading v-if="loading" class="loading" type="spinner" color="#1989fa" size="50" />

    <!-- 圆角弹窗（顶部） -->
    <van-popup v-model:show="showCategoryMenu" round position="top">
      <div class="popup">
        <div
          class="category"
          v-for="(category, index) in categories"
          :key="index"
          @click="handelClickShowType(category.showTypeName)"
        >
          <!-- { "title": "全部", "showType": 0,"showTypeName": "All"} -->
          <img :src="getImageUrl(index)" class="icon" @error="handleImageError" />
          <div class="title">{{ category.title }}</div>
        </div>
      </div>
    </van-popup>

    <!-- 搜索和筛选组件 -->
    <van-sticky>
      <div class="sticky-content">
        <!-- 搜索框 -->
        <SearchBar v-show="!loading" :keyword="Keyword" :currentPosition="currentPosition" />
        <!-- 分类和筛选条件-->
        <Filter
          ref="filter"
          v-show="!loading"
          @update:loading="changeLoadingStatus"
          @openCategoryPopup="handelOpenCategoryPopup"
          @close:loading="handleCloseLoading"
          :clearDate="clearDate"
          :clearTag="clearTag"
          :clearCity="clearCity"
          :showTypeName="selectedShowTypeName"
          :routeSorting="routeSorting"
          :routeShowTypeName="routeShowTypeName"
          :routeShowType="routeShowType"
          @resetTagComplete="resetTagComplete"
          @showMoreTags="showMoreTags"
        />
      </div>
    </van-sticky>

    <!-- 演出列表 -->
    <CategoryList
      class="list"
      ref="categoryList"
      v-show="!loading"
      :showList="showList"
      :hasMore="hasMore"
      :closeLoading="closeLoading"
      @loadMore="LoadMore"
      @resetDate="resetDate"
      @resetTag="resetTag"
      @resetCity="resetCity"
      @changeTag="changeTag"
    />

    <!-- 更多tag 选项 -->
    <more-tags ref="moreTags" />

    <!-- 底部tabbar -->
    <TabBar v-show="!loading" />
  </div>
</template>

<script setup>
import CategoryList from '@/component/category/CategoryList.vue'
import SearchBar from '@/component/common/SearchBar.vue'
import Filter from '@/component/category/Filter.vue'
import MoreTags from '@/component/category/MoreTags.vue'
import TabBar from '@/component/common/TabBar.vue'

import { ref, computed, onMounted, useTemplateRef } from 'vue'
import { useStore } from '@/stores/index.js'
const store = useStore()

import { useRouter, useRoute } from 'vue-router'
const router = useRouter()
const route = useRoute()

const routeSorting = computed(() => route.query.sorting)
const routeShowTypeName = computed(() => route.query.showTypeName)
const routeShowType = computed(() => route.query.showType)

const filterRef = useTemplateRef('filter')
// 是否还有更多数据
const hasMore = computed(() => filterRef.value?.hasMore)
// 演出列表
const showList = computed(() => filterRef.value?.showList)

const categoryListRef = useTemplateRef('categoryList')

/*  变量 属性 */
const loading = ref(true)
const Keyword = ref('搜索明星、演出、赛事、场馆')

const closeLoading = ref(false)

//分类弹出层菜单
const showCategoryMenu = ref(false)

const selectedShowTypeName = ref('')

//弹窗分类
const categories = ref([])

// 批量导入 showTypes 目录下的所有图片
const showTypeImages = import.meta.glob('@/asset/images/showTypes/*.png', {
  eager: true,
  query: '?url',
  import: 'default',
})

// 创建图片名称到URL的映射
const showTypeImageMap = ref({})

const clearDate = ref(false)
const clearTag = ref(0)
const clearCity = ref(false)

onMounted(() => {
  Object.keys(showTypeImages).forEach((key) => {
    const fileName = key
      .split('/')
      .pop()
      .replace(/\.png$/i, '')
    showTypeImageMap.value[fileName] = showTypeImages[key]
    // console.log(`映射 ${fileName} => ${showTypeImages[key]}`)
  })
})

/* 计算属性 */
//当前定位 或者手动设定的城市名字
const currentPosition = computed(() => {
  return store.currentCity.cityName
})

/* 方法 */

//改变 页面loading状态方法
const changeLoadingStatus = (status) => {
  loading.value = status
}

// 演出列表每一页加载完毕
const handleCloseLoading = (bool) => {
  // 添加边界检查
  if (closeLoading.value !== undefined) {
    closeLoading.value = bool
  }
}

//打开弹窗
const handelOpenCategoryPopup = ({ bool, category }) => {
  // console.log('{ bool, category }', bool, category)
  // 添加边界检查
  if (showCategoryMenu.value !== undefined && categories.value !== undefined) {
    showCategoryMenu.value = bool
    categories.value = category
  }
}

const handelClickShowType = (typeName) => {
  //切换showType
  // showToast(typeName)

  // 更新类型
  selectedShowTypeName.value = typeName

  // 关闭弹窗
  showCategoryMenu.value = false
}

const getImageUrl = (index) => {
  // 如果是数字索引，转换为字符串
  const key = index.toString()
  return showTypeImageMap.value[key] || ''
}

//加载下一页演出列表数据
const LoadMore = async () => {
  // 添加边界检查
  if (!filterRef.value || !categoryListRef.value) {
    console.warn('组件引用为空，跳过加载更多操作')
    return
  }

  try {
    await filterRef.value.handleLoadMore()
    // 成功加载后，确保设置加载状态为 false
    if (categoryListRef.value) {
      categoryListRef.value.setLoading(false)
    }
  } catch (error) {
    console.error('加载更多数据出错:', error)
    // 出错时也要更新加载状态
    if (categoryListRef.value) {
      categoryListRef.value.setLoading(false)
      categoryListRef.value.setFinished(true)
    }
  }
}

const resetDate = () => {
  clearDate.value = true
}

const resetTag = () => {
  // clearTag.value = true
  clearTag.value++
}

const resetTagComplete = () => {
  clearTag.value = 0
}

const resetCity = () => {
  clearCity.value = true
}

const changeTag = (tag) => {
  // 添加边界检查
  if (filterRef.value) {
    // filterRef.value.clickTag(tag)
    // 通过修改 clearTag 来触发 tag 清除逻辑
    clearTag.value++
  }
}

const moreTagsRef = useTemplateRef('moreTags')

// 显示更多tags
const showMoreTags = () => {
  // 添加边界检查
  if (moreTagsRef.value) {
    moreTagsRef.value.openMoreTags()
  }
}

// const gotoPage = (type) => {
//   if (type === 'search') {
//     router.push({ path: '/search' })
//   }
// };
</script>

<style scoped lang="scss">
.container {
  position: relative;
  min-height: 100vh;

  .loading {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }

  .popup {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    text-align: center;
    padding: 15px;
    gap: 20px;

    .category {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;

      .icon {
        width: 100%;
        max-width: 50px;
        height: auto;
      }

      .title {
        font-size: 14px;
        color: #333;
        text-align: center;
        font-weight: 500;
      }
    }
  }

  .sticky-content {
    background: #fff;
    width: 100%;
    padding-bottom: 10px;
  }

  .list {
    // margin-bottom: 50px;
  }

  .tabbar {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
  }
}
</style>
